import { CdtMetaParam } from '@/types/role';
import { PlusOutlined, SaveOutlined } from '@ant-design/icons';
import { Button, Col, Input, InputRef, message, Row, Tag } from 'antd';
import { useEffect, useRef, useState } from 'react';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useUpdateLayoutEffect } from 'ahooks';

interface Props {
  param: CdtMetaParam;
  style: React.CSSProperties;
  onParamChange: (param: CdtMetaParam) => void;
}
const CdtMetadataItem = ({ param, onParamChange, style }: Props) => {
  const [inputVisible, setInputVisible] = useState(false);
  const [paramLable, setParamLable] = useState('');
  const [inputValue, setInputValue] = useState('');
  const [tags, setTags] = useState<string[]>([]);
  const inputRef = useRef<InputRef>(null);
  const { isPc } = useWindowWidth();
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const updateTags = (tags: string[])=>{
    setTags(tags);
    onParamChange({ ...param, label: paramLable, values: tags });
  }

  const handleInputConfirm = () => {
    if (inputValue && param.values.indexOf(inputValue) === -1) {
      updateTags([...tags, inputValue]);
    }
    setInputVisible(false);
    setInputValue('');
  };

  const handleClose = (index: number) => {
    const newTags = tags.filter((_, i) => i !== index);
    updateTags(newTags);
  };

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  useEffect(() => {
    setTags(param.values);
    setParamLable(param.label);
  }, [param]);

  useUpdateLayoutEffect(()=>{
    onParamChange({ ...param, label: paramLable, values: tags });
  },[paramLable])

  return (
    <div className="mb-2 rounded-lg bg-[#f3f3f3]">
      <Row gutter={16} key={param.id}>
        <Col className="gutter-row content-center" span={8}>
          <div style={style} className="ml-2 truncate text-center">
            {param.key}
          </div>
        </Col>
        <Col className="gutter-row content-center" span={2}>
          <div style={style} className="truncate text-center">
            {param.data_type}
          </div>
        </Col>
        <Col className="gutter-row content-center" span={6}>
          <div style={style}>
            <Input
              className="role-form-input text-center"
              value={paramLable}
              bordered={false}
              onChange={(e) => {
                setParamLable(e.target.value);
              }}
            ></Input>
          </div>
        </Col>
        <Col className="gutter-row content-center" span={8}>
          <div style={style} className="flex flex-wrap gap-1">
            {tags.map((value, index) => {
              return (
                <div key={`tag_${param.id}_${param.key}_${index}`}>
                  <Tag
                    className="role-tag"
                    closable
                    onClose={() => {
                      handleClose(index);
                    }}
                  >
                    {value}
                  </Tag>
                </div>
              );
            })}
            {inputVisible && (
              <Input
                ref={inputRef}
                size="small"
                className="role-form-input"
                placeholder='输入可选值，【Enter】保存'
                style={{ minWidth: 78 }}
                value={inputValue}
                onChange={handleInputChange}
                onBlur={handleInputConfirm}
                onPressEnter={handleInputConfirm}
              />
            )}
            {!inputVisible && (
              <Tag
                onClick={() => {
                  setInputVisible(true);
                }}
                className="role-tag cursor-pointer"
              >
                <PlusOutlined /> 添加
              </Tag>
            )}
          </div>
        </Col>
        {/* <Col className="gutter-row content-center" span={2}>
          <div style={style}>
            <Button type='text' icon={<SaveOutlined />} onClick={handleSave}>{isPc ? "保存" : ""}</Button>
          </div>
        </Col> */}
      </Row>
    </div>
  );
};

export default CdtMetadataItem;
